//
//  BFHomeViewController.m
//  13KModel
//
//  Created by jack on 27/08/12.
//  Copyright (c) 2012 butterfly. All rights reserved.
//
// CLASS INCLUDES
#import "BFCategoryLabel.h"
#import "BFAutoBackgroundView.h"
#import "BFHomeViewController.h"

// SYSTEM INCLUDES

// CONST DEFINE
NSInteger const kVItemNum = 2;
NSInteger const kHItemNum = 3;
CGFloat const kTopMargin = 65.0f;
CGFloat const kLeftMargin = 20.0f;
//CGFloat const kLeftMargin = 40.0f;
CGFloat const kMidMargin = 15.0f;
CGFloat const kEntryWidth = 110.0f;
CGFloat const kEntryHight = 110.0f;
CGFloat const kOneStep = 5.0f;

@interface BFHomeViewController (){
    NSArray *groupName;
}

@property (nonatomic) NSInteger prevPage;
@property (nonatomic) CGRect prevFrame;
@property (nonatomic) CGFloat prevX;

- (void)initColumns;
- (void)initBackground;
- (void)addColumnEntry:(NSDictionary*)data section:(NSInteger)aSection index:(NSInteger)aIndex;
@end

@implementation BFHomeViewController
@synthesize prevX = _prevX, prevFrame = _prevFrame, prevPage = _prevPage;
@synthesize scrollView = _scrollView, pageControl = _pageControl;
@synthesize categoryLabel = _categoryLabel;
@synthesize autoBackgroundView = _autoBackgroundView;

- (void)viewDidLoad
{
    [super viewDidLoad];  
    
    gridItems = [NSMutableArray array];
    [self initColumns];
    [self initBackground];
}

- (void)viewDidUnload
{
    columnDict = nil;
    gridItems = nil;
    [self setCategoryLabel:nil];
    [self setAutoBackgroundView:nil];
    [self setScrollView:nil];
    [self setPageControl:nil];
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (animated) {
        [self.autoBackgroundView updateBackground:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [self.navigationController.navigationBar setHidden:NO];
    [super viewDidDisappear:animated];
}

#pragma mark- private methods
- (void)initColumns
{
    // 读取配置
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"column_cfg" ofType:@"plist"];
    columnDict = [[NSMutableDictionary alloc] initWithContentsOfFile:resourcePath];
    
    // 分类
    groupName = (NSArray*)[columnDict valueForKey:@"CategoryName"];
    
    // 加载数据
    NSInteger section = 0;
    for (NSString *group in groupName) {
        
        NSInteger index = 0;    
        for (NSDictionary *dic in [columnDict valueForKey:group]) {
            [self addColumnEntry:dic section:section index:index++];
        }
        section++;
    }
}

- (void)initBackground
{
    // test
    _categoryLabel = [[BFCategoryLabel alloc] initWithFrame:CGRectMake(20, 15, 120, 40)];
    _categoryLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_categoryLabel];
    [self.categoryLabel updateTitleText:[groupName objectAtIndex:0] toLeft:YES];
    
    self.autoBackgroundView.isMaskSupported = YES;
    self.autoBackgroundView.imageArray = [NSArray arrayWithObjects:@"background.jpeg",
                                                                   @"background_1.jpeg",
                                                                   @"background_2.jpeg",
                                                                   @"background_3.jpeg",
                                                                   @"background_4.jpeg",
                                                                   @"background_5.jpeg",
                                                                   @"background_6.jpeg",
                                                                   @"background_7.jpeg",
                                                                   @"background_8.jpeg",
                                                                   @"background_9.jpeg",
                                                                   @"background_10.jpeg",
                                                                   @"background_11.jpeg",
                                                                   @"background_12.jpeg",
                                                                   @"background_13.jpeg",
                                                                   nil];
}

- (void)addColumnEntry:(NSDictionary*)data section:(NSInteger)aSection index:(NSInteger)aIndex
{
    // 当前栏目总数
    NSInteger page = aSection + 1;
    NSInteger index = aIndex;
    
    // 坐标位置
    CGFloat posX = kLeftMargin+(index%kVItemNum)*(kEntryWidth+kMidMargin)+(page-1)*self.scrollView.frame.size.width;
    CGFloat posY = kTopMargin+(index/kVItemNum)*(kEntryHight+kMidMargin);
    NSString *icon = [NSString stringWithFormat:@"%@.png", [data valueForKey:@"screen_name"]];
    BFGridItem *item = [[BFGridItem alloc] initWithTitle:[data valueForKey:@"title"]
                                               imageName:icon
                                                section:aSection
                                                 atIndex:aIndex 
                                                editable:YES];
    item.frame = CGRectMake(posX, posY, kEntryWidth, kEntryHight);
    item.delegate = self;
    [self.scrollView addSubview:item];
    [gridItems addObject:item];
    
    [self.pageControl setNumberOfPages:page];
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width*page, 
                                               self.scrollView.frame.size.height)];
}

#pragma mark- UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGRect frame = self.autoBackgroundView.frame;
    frame.origin.x = self.prevFrame.origin.x + (self.prevX - self.scrollView.contentOffset.x)/kOneStep;
    
    if (frame.origin.x<=0 && frame.origin.x>self.scrollView.frame.size.width-frame.size.width) {
        self.autoBackgroundView.frame = frame;
    }
    
    // 重置索引位置
    self.pageControl.currentPage = self.scrollView.contentOffset.x/self.scrollView.frame.size.width;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.prevPage = self.pageControl.currentPage;
    self.prevX = self.scrollView.contentOffset.x;
    self.prevFrame = self.autoBackgroundView.frame; 
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSString *category = [groupName objectAtIndex:self.pageControl.currentPage];
    if (category && ![category isEqualToString:self.categoryLabel.textLabel.text]) {
        [self.categoryLabel updateTitleText:category toLeft:self.prevPage<self.pageControl.currentPage];
    }
}

#pragma mark- BFGridItemDelegate

- (void)gridItemDidClicked:(BFGridItem *) gridItem
{   
    if (gridItem.isEditing) {
        gridItem.isEditing = NO;
    }
    else {
        if (![wbEngine isLoggedIn] || [wbEngine isAuthorizeExpired]) {
            // 登录状态提示
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"登录新浪微博", @"information", nil)
                                                            message:NSLocalizedStringFromTable(@"亲,您还未登录新浪微博,是否现在登录?", @"message", nil)
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedStringFromTable(@"取消", @"information", nil)
                                                  otherButtonTitles:NSLocalizedStringFromTable(@"登录", @"information", nil), nil];
            [alert show];
            return;
        }
        
        // 访问指定微博账号主页
        NSDictionary *dic = [[columnDict valueForKey:[groupName objectAtIndex:gridItem.section]] objectAtIndex:gridItem.index];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setValue:[dic valueForKey:@"screen_name"] forKey:@"screen_name"];
        [userDefault setValue:[dic valueForKey:@"title"] forKey:@"title"];
        
        // 切换到微博详情
        UIViewController *statusViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"Status"];
        [self.navigationController pushViewController:statusViewController animated:YES];
        
        // 添加事件
        [[GANTracker sharedTracker] trackEvent:@"Column"
                                        action:@"Click"
                                         label:[dic valueForKey:@"screen_name"]
                                         value:1
                                     withError:nil];
    }
}

- (void)gridItemDidEnterEditingMode:(BFGridItem *) gridItem
{
    gridItem.isEditing = YES;
}

- (void)gridItemDidDeleted:(BFGridItem *) gridItem aSection:(NSInteger)section atIndex:(NSInteger)index
{
    [gridItems removeObject:gridItem];
    
    [UIView animateWithDuration:0.2 animations:^{
        CGRect lastFrame = gridItem.frame;
        CGRect curFrame;
        for (int i=index; i < [gridItems count]; i++) {
            BFGridItem *temp = [gridItems objectAtIndex:i];
            curFrame = temp.frame;
            [temp setFrame:lastFrame];
            lastFrame = curFrame;
            [temp setIndex:i];
        }
    }];
    
    [gridItem removeFromSuperview];
    gridItem = nil;
}

- (void)gridItemDidMoved:(BFGridItem *) gridItem withLocation:(CGPoint)point  
   moveGestureRecognizer:(UILongPressGestureRecognizer*)recognizer
{
}

- (void)gridItemDidEndMoved:(BFGridItem *) gridItem withLocation:(CGPoint)point 
       moveGestureRecognizer:(UILongPressGestureRecognizer*) recognizer
{
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self performSelector:@selector(wbLogin) withObject:self afterDelay:0.5f];
    }
}

- (void)wbLogin
{
    [wbEngine logIn];
}
@end
